<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">	
<title>智能语音识别以及合成播放示例</title>
 <script src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js" type="text/javascript" charset="utf-8"></script>
<script src="${pageContext.request.contextPath}/js/HZRecorder.js"></script>
<script type="text/javascript">
	
	//这个是初始化语音 当然也可以用 流播放了~
	var audio3 = new Audio("${pageContext.request.contextPath}/voice/huanying.mp3");
	audio3.play();
	
	/* 音频 */
	var recorder;
	var audio = document.querySelector('audio');//用于合成录音
	//开始录音
	function startRecording() {
		HZRecorder.get(function(rec) {
			recorder = rec;
			recorder.start();
		});
	}
	//获取录音
	function obtainRecord() {
		var record = recorder.getBlob();
	};
	//停止录音
	function stopRecord() {
		recorder.stop();
	};

	function playRecord() {
		recorder.play(audio);
	};
		
	//保存录音
	function uploadRecord(){
		//上传录音地址
		recorder.upload("${pageContext.request.contextPath}/voiceSpeech/save.do", function (state, e) {
			switch (state) {
                   case 'uploading':
                       break;
                   case 'ok':   
                   	var map = JSON.parse(e.target.response);
                       if (map["success"]) {
                       	var Rtext = map["Rtext"];
                       	var res = map["res"];
                       	$("#voice").html(Rtext);//语音识别内容
                       	$("#res").html(res);//语音合成内容
						var base64Data = map["base64Data"];//语音合成音频数据base64
// 						console.log(base64Data);
						var audio2 = document.getElementById('aud');//用于播放合成语音
						audio2.src = window.URL.createObjectURL(getBlob(base64Data));//生成blob 路径
						audio2.autoplay = true;//播放
           	   		} else {
           	   			alert("保存失败");
           	   		} 
                       break;
                   case 'error':
                       alert("上传失败");
                       break;
                   case 'cancel':
                       alert("上传被取消");
                       break;
               }
         });
	}
		
	//根据base64音频数据 转化为 blob对象
	function getBlob(base64Data){
		var dataURI = "data:audio/wav;base64,"+base64Data; //base64 字符串
	    var mimeString =  dataURI.split(',')[0].split(':')[1].split(';')[0]; // mime类型
	    var byteString = atob(dataURI.split(',')[1]); //base64 解码
	    var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
	    var intArray = new Uint8Array(arrayBuffer); //创建视图
	    for (i = 0; i < byteString.length; i += 1) {
	         intArray[i] = byteString.charCodeAt(i);
	    }
	    return new Blob([intArray], { type:  "audio/wav" }); //转成blob
	}        
	
	//动态图标
	function recordSave(flag){
		if('begin' == flag){
			$(".voice_before").hide();
		   	$(".voice_after").show();
		   	//停止播放方法
// 			audio.pause();
// 			audio.currentTime = 0;
			startRecording();//开始录音
		}
		if('end' == flag){
			$(".voice_before").show();
		   	$(".voice_after").hide();
			obtainRecord();//获取录音
			stopRecord();//停止录音
			uploadRecord();//上传录音
		}
	}
	function recordStop() {
		$(".voice_before").show();
	   	$(".voice_after").hide();
		obtainRecord();//获取录音
		stopRecord();//停止录音
		uploadRecord();//上传录音
	}
	</script>
	
	<!-- 	按钮初始化状态 -->
	<style type="text/css">
		.show{ display:block;}
		.hide{ display: none;}
		.robot_talk .talk_left .talk_bottom{margin: 15px auto; cursor: pointer;}
		/*这是左右布局样式*/
		.div-a{ float:left;width:49%;height:500px;border:1px solid #F00} 
		.div-b{ float:left;width:49%;height:500px;border:1px solid #000} 
		span{ font-size:25px }
	</style>
</head>
<body>
	<audio id="aud"></audio>
	<h1>H5语音识别以及语音合成（录音和播放） 测试</h1>
	<div class="div-a">
		
		<h2>用测试按钮 1 手动点击开始和保存测试</h2>
		<!-- 测试按钮 1-->
		<input type="button" value="开始录音" onclick="startRecording()" />
		<input type="button" value="保存录音" onclick="uploadRecord()" />
		<!-- 测试按钮 1-->
		
		<h2>用测试按钮 2 不说话自动停止录音测试</h2>
		<!-- 测试按钮 2-->
		<div class="talk_bottom" style="width:450px;height:160px">
			<img onclick="recordSave('begin');" src="${pageContext.request.contextPath}/images/voice/ico_voice.png" width="137" height="137" class="voice_before" style="display: block; margin:26px auto 0px auto;"/>
			<img onclick="recordSave('end');" src="${pageContext.request.contextPath}/images/voice/ico_voice02.gif" width="450" height="160"  class="voice_after hide"/>
		</div>
		<!-- 测试按钮 2-->
		
	</div>
 	<!-- 右边区域 -->
	<div class="div-b" >
		<span style="color:red">测试逻辑1：您说"你好",机器人回复 "我知道你也很好呀"</span><br/><br/>
		<span>语音识别结果：</span><span id="voice"></span><br/>
		<span>机器人回复结果：</span><span id="res"></span><br/>
	</div> 
 
</body>
</html>